package com.wechat.scheme.controller;

import com.google.common.collect.Maps;
import com.wechat.scheme.config.WxMpProperties;
import com.wechat.scheme.entity.SchemeUser;
import com.wechat.scheme.entity.model.EleSelectOp;
import com.wechat.scheme.entity.model.LoginModel;
import com.wechat.scheme.entity.model.SchemeUserVo;
import com.wechat.scheme.repo.SchemeUserRepo;
import com.wechat.scheme.response.Response;
import com.wechat.scheme.jwt.JWTProvideSerivce;
import com.wechat.scheme.jwt.ShiroKit;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
public class AdminLoginController {

    @Autowired
    SchemeUserRepo schemeUserRepo;

    @Autowired
    JWTProvideSerivce jwtProvideSerivce;

    @PostMapping(value="/login")
    public Response login(HttpServletResponse response, @RequestBody LoginModel user) {
        SchemeUser schemeUser = schemeUserRepo.findUserByUsername(user.getUsername());
        if(null == schemeUser) return Response.fail(40003,"用户名错误");
        String pass = ShiroKit.sha256(user.getPassword(),schemeUser.getSolt());
        if(! schemeUser.getPassword().equals(pass)) return Response.fail(40001,"密码错误");
        String token = jwtProvideSerivce.createJWTToken(schemeUser.getId(),schemeUser.getUsername());
        Map<String,Object> map = Maps.newHashMap();
        map.put("token",token);
        map.put("user",schemeUser);
        return Response.succeed(map);
    }

    @GetMapping("/user/info")
    public Response userInfor(){
        SchemeUserVo vo = SchemeUserVo.builder()
                .roles(Arrays.asList("admin"))
                .avatar("http://www.qqju.com/pic/tx/tx37457.jpg")
                .name("super admin")
                .build();
        return Response.succeed(vo);
    }

    @PostMapping("/loginout")
    public Response loginout(){
        return Response.succeed();
    }

    @Autowired
    WxMpProperties wxMpProperties;

    @GetMapping("/list/appid")
    public Response listAppid(){
        List<WxMpProperties.MpConfig> configs = wxMpProperties.getConfigs();
        List<EleSelectOp> appids = configs.stream().map(p -> {
            return EleSelectOp.builder()
                    .label(p.getAppId())
                    .value(p.getAppId())
                    .build();
        }).collect(Collectors.toList());
        return Response.succeed(appids);
    }




}
